//
//  AppDelegate.swift
//  Weibo
//
//  Created by 孙明海 on 16/1/23.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
//        QorumLogs.enabled = true
//        
//        QL1Debug("哈哈哈")
        
        
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        setupApperence()
        
        window = UIWindow()
        window?.backgroundColor = UIColor.whiteColor()
        
        // 测试
//        window?.rootViewController = UINavigationController(rootViewController: ComposeViewController())
        
        window?.rootViewController = defaultRootViewController
        
        
        
        window?.makeKeyAndVisible()
        
        
        //监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBSwitchRootViewControllerNotification,
            object: nil,
            queue: nil) { (notification) -> Void in
                if notification.object != nil {
                    self.window?.rootViewController = WelcomeViewController()
                    return
                }
                self.window?.rootViewController = MainViewController()
        }
        
        return true
    }
    
    /// 程序进入到后台
    func applicationDidEnterBackground(application: UIApplication) {
        StatusDAL.clearCacheData()
    }
    
    //销毁通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WBSwitchRootViewControllerNotification, object: nil)
    }
    

    //设置外观
    private func setupApperence() {
        UINavigationBar.appearance().tintColor = WBAppearenceColor
        UITabBar.appearance().tintColor = WBAppearenceColor
    }

}

//切换根视图
extension AppDelegate {
    //获取跟控制器
    private var defaultRootViewController: UIViewController {
        //是否登陆
        if !UserAccountViewModel.sharedUserAccount.userLogin {
            return MainViewController()
        }
        //版本是否更新
        return isNewVersion ? NewFeatureCollectionViewController() : WelcomeViewController()
    }
    
    //判断是否版本是否更新
    private var isNewVersion: Bool {
        //获取当前版本
       let version = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)
        //获取以前版本
        let versionKey = "versionKey"
        let oldVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        
        NSUserDefaults.standardUserDefaults().setDouble(version!, forKey: versionKey)
        return version > oldVersion
    }
}

